package com.smarthome.api.ipc;

import java.util.HashMap;
import java.util.Map;

import org.apache.commons.httpclient.HttpStatus;
import org.springframework.stereotype.Service;

import com.smarthome.common.httpwapper.HttpRequester;
import com.smarthome.common.httpwapper.HttpResponse;

@Service("ipcCommandService")
public class IpcCommandService {

    /**
     * 手机端调用工控机方法
     * 
     * @param ipcUrl 工控机ip:port
     * @param command 工控机命令，比如 IpcConstants.IPC_COMMAND_RESIDENCE_DOOR_HK
     * @param method 执行方法，比如 doCmd
     * @param params
     * @return
     * @author KongXiangyu
     */
    public String sendCommand(String ipcUrl, String command, String method, Map<String, String> params) {
        if (null == params)
            params = new HashMap<String, String>();
        params.put("command", command);
        params.put("method", method);
        try {
            HttpResponse response = HttpRequester.sendGet(formatParam(ipcUrl,params), params);
            if (response.getStatusCode() == HttpStatus.SC_OK)
                return response.getBody();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    
    private String formatParam(String ipcUrl,Map<String, String> params){
    	StringBuilder url = new StringBuilder(ipcUrl+"?");
    	for(String key : params.keySet()){
    		url.append(key);
    		url.append("=");
    		url.append(params.get(key));
    		url.append("&");
    	}
    	return url.toString();
    }
}
